package com.xuexi.mashibing;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockExample {
    private final ReentrantReadWriteLock readWriteLock;

    // 初始化读写锁
    public ReadWriteLockExample() {
        readWriteLock = new ReentrantReadWriteLock();
    }

    // 读取数据的方法，使用读锁
    public void readData() {
        readWriteLock.readLock().lock();
        try {
            // 读取数据
            System.out.println("读取数据...");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放读锁
            readWriteLock.readLock().unlock();
        }
    }

    // 写入数据的方法，使用写锁
    public void writeData() {
        readWriteLock.writeLock().lock();
        try {
            // 写入数据
            System.out.println("写入数据...");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放写锁
            readWriteLock.writeLock().unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReadWriteLockExample example = new ReadWriteLockExample();

        // 创建多个线程执行读取操作
        for (int i = 0; i < 3; i++) {
            new Thread(example::readData).start();
        }

        // 创建一个线程执行写入操作
        Thread writerThread = new Thread(example::writeData);
        writerThread.start();
        // 等待写入线程执行完毕
        writerThread.join();

        // 所有读写操作完成后，程序结束
        System.out.println("读写操作完成，退出程序.");
    }
}
